package logger

import (
	"context"
	"fmt"
	"github.com/google/wire"
	"sieve_admin_server/app/dao"
	"sieve_admin_server/app/schema"
	serviceSys "sieve_admin_server/app/service/sys"
	"strings"
	"time"
)

var (
	LoginSet = wire.NewSet(wire.Struct(new(LoginSrv), "*"))
)

type LoginSrv struct {
	RoleSrv         *serviceSys.RoleSrv
	LoginRecordRepo *dao.LoginRecordRepo
}

func (a *LoginSrv) Query(ctx context.Context, uid, roleId uint64, reqArgs map[string]interface{}, p schema.PaginationParam, repKeys []string) interface{} {

	var leaderCondition string
	if a.RoleSrv.IsSalespersonRole(roleId) {
		leaderCondition = fmt.Sprintf(" AND (user.id = %v OR user.leader_id = %v OR user.top_leader_id = %v)", uid, uid, uid)
	}

	var (
		joinString = []string{
			fmt.Sprintf(`INNER JOIN user ON user.id = login_record.creator AND user.deleted = 0 %v`, leaderCondition),
		}
	)

	context.WithValue(ctx, "join", strings.Join(joinString, " "))

	req, err := a.LoginRecordRepo.Query(ctx, reqArgs, p, repKeys)
	if err != nil {
		return err
	}
	return req
}

func (a *LoginSrv) Create(ctx context.Context, userId uint64, item map[string]interface{}) interface{} {

	var (
		now = time.Now().Unix()
		def = map[string]interface{}{
			"creator":    userId,
			"create_at":  now,
			"updated_at": now,
		}
	)

	for k, v := range def {
		item[k] = v
	}

	return a.LoginRecordRepo.Create(ctx, item)
}
